﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Data;
using System.Text;
using System.Xml;
using CE.InputOut;
using CE.Database;

/// <summary>
/// Summary description for WegoHotels
/// </summary>
/// 
namespace CE.Wego
{
    public class WegoHotels
    {
        const string API_KEY = "c08b4c9e";
        public WegoHotels()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public string GetSearchId(string locationid, string checkin, string checkout)
        {
            string searchid = "";

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://www.wego.com/api/hotels/search/new?location_id=" + locationid + "&check_in=" + checkin + "&check_out=" + checkout + "&format=json&api_key=" + API_KEY);

                //http://www.wego.com/api/hotels/search/new?location_id=7046&check_in=20110815&check_out=20110818&format=xml&api_key=c08b4c9e
                req.Method = "GET";
                req.Referer = "http://www.comparexpress.com";
                HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader answer = new StreamReader(stream);
                searchid = answer.ReadToEnd();

                string jsonvalues = searchid.Substring(14, searchid.IndexOf('}') - 15);
                searchid = jsonvalues;
            }
            catch (WebException Wex)
            {
                CreateExceptionLog(Wex, "DataSet SearchHotel(string locationid, string checkin, string checkout)");
            }
            catch (Exception Ex)
            {
                CreateExceptionLog(Ex, "DataSet SearchHotel(string locationid, string checkin, string checkout)");
            }
            return searchid;

        }

        public void SearchHotel(out bool isdone, out string message, string searchid, string cxsearchid, string textfilter, string district, string price_min, string price_max, string sortby, string order, string page, Int32 per_page)
        {
            string hotelresults = "";
            isdone = false;
            message = "";
            //try
            //{               
                //hotelresults = GetResponse("http://www.wego.com/api/hotels/search/" + searchid + "?text_filter=" + textfilter +
                //    "&sort=" + sortby + "&lang=en&currency=SGD&format=xml" + "&price_min=" + price_min + "&price_max=" + price_max +
                //    "&order=" + order + "&page=" + page + "&per_page=" + per_page + "&api_key=" + API_KEY);

                hotelresults = GetResponse("http://www.wego.com/api/hotels/search/" + searchid + "?text_filter=" + textfilter +
                   "&lang=en&currency=SGD&format=xml&api_key=" + API_KEY);

           
               if (hotelresults.Length > 0)
                {
                    if (hotelresults.Substring(0, 5) == "<?xml")
                    {
                        isdone = HotelResultsXMLtoTable(hotelresults, cxsearchid);


                        WegoHotelsDB wegodb2 = new WegoHotelsDB();
                        wegodb2.UpdateSearch(Convert.ToInt64(cxsearchid));
                        
                    }
                    else
                    {
                        message = hotelresults;
                        isdone = false;
                    }
                }
                else
                    SearchHotel(out isdone, out message, searchid, cxsearchid, textfilter, district, price_min, price_max, sortby, order, page, per_page);

            //}
            //catch (WebException Wex)
            //{
            //    CreateExceptionLog(Wex, "string SearchHotel(string searchid)");
            //}
            //catch (Exception Ex)
            //{
            //    CreateExceptionLog(Ex, "string SearchHotel(string searchid)");
            //}
            //return isdone;
        }

        public bool HotelResultsXMLtoTable(string results, string cxsearchid)
        {
            bool isDone = false;

            WegoHotelsDB wegodb = new WegoHotelsDB();
            WegoHotelsInfo wegoinfo = new WegoHotelsInfo();
            WegoHotelsRateInfo wegorateinfo = new WegoHotelsRateInfo();
            WegoHotelsRateDB wegoratedb = new WegoHotelsRateDB();

            string Currency = "";
            string SortBy = "";
            string OrderBy = "";
            string RecCount = "";
            string FilteredCount = "";
            string TotalCount = "";
            string ID = "";
            string HotelName = "";
            string Description = "";
            string Stars = "";
            string Address = "";
            string Image = "";
            string Satisfaction = "";
            string Rank = "";
            string Latitude = "";
            string Longitude = "";
            string Type = "";
            string Num_Reviews = "";
            string Num_Positive_Reviews = "";
            string Num_Negative_Reviews = "";
            string Num_Neutral_Reviews = "";

            float Price = 0;
            bool isTax = false;
            bool onRequest = false;
            string RateDescription = "";
            string Partner = "";
            string KeyId = "";

            Int64 cxhotelid = 0;

         
            try
            {
                XmlTextReader reader = new XmlTextReader(new StringReader(results));
                StringBuilder sb = new StringBuilder();

                string fieldname = "";
                bool isHotel = false;
                bool isRate = false;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {

                        if (reader.Name == "currency")
                        {
                            fieldname = "currency";
                        }

                        if (reader.Name == "sort")
                        {
                            fieldname = "sort";
                        }

                        if (reader.Name == "order")
                        {
                            fieldname = "order";
                        }

                        if (reader.Name == "count")
                        {
                            fieldname = "count";
                        }

                        if (reader.Name == "filtered_count")
                        {
                            fieldname = "filtered_count";
                        }

                        if (reader.Name == "total_count")
                        {
                            fieldname = "total_count";
                        }

                        if (reader.Name == "district")
                        {
                            isHotel = false;
                        }

                        if (reader.Name == "hotel")
                        {
                            isHotel = true;
                        }

                        if (isHotel && reader.Name == "id")
                        {
                            fieldname = "id";
                        }

                        //HotelName
                        if (isHotel && reader.Name == "name")
                        {
                            fieldname = "name";
                        }

                        if (isHotel && reader.Name == "description")
                        {
                            fieldname = "description";
                        }

                        if (isHotel && reader.Name == "stars")
                        {
                            fieldname = "stars";
                        }

                        if (isHotel && reader.Name == "address")
                        {
                            fieldname = "address";
                        }

                        if (isHotel && reader.Name == "image")
                        {
                            fieldname = "image";
                        }

                        if (isHotel && reader.Name == "satisfaction")
                        {
                            fieldname = "satisfaction";
                        }

                        if (isHotel && reader.Name == "rank")
                        {
                            fieldname = "rank";
                        }

                        if (isHotel && reader.Name == "latitude")
                        {
                            fieldname = "latitude";
                        }

                        if (isHotel && reader.Name == "longitude")
                        {
                            fieldname = "longitude";
                        }

                        if (isHotel && reader.Name == "type")
                        {
                            fieldname = "type";
                        }

                        if (isHotel && reader.Name == "num_reviews")
                        {
                            fieldname = "num_reviews";
                        }

                        if (isHotel && reader.Name == "num_positive_reviews")
                        {
                            fieldname = "num_positive_reviews";
                        }

                        if (isHotel && reader.Name == "num_negative_reviews")
                        {
                            fieldname = "num_negative_reviews";
                        }

                        if (isHotel && reader.Name == "num_neutral_reviews")
                        {
                            fieldname = "num_neutral_reviews";
                        }

                        if (reader.Name == "rate")
                        {
                            isHotel = false;
                            isRate = true;
                        }

                        if (isRate && reader.Name == "price")
                        {
                            fieldname = "price";
                        }

                        if (isRate && reader.Name == "tax")
                        {
                            fieldname = "tax";
                        }

                        if (isRate && reader.Name == "on_request")
                        {
                            fieldname = "on_request";
                        }

                        if (isRate && reader.Name == "description")
                        {
                            fieldname = "ratedescription";
                        }

                        if (isRate && reader.Name == "partner")
                        {
                            fieldname = "partner";
                        }

                        if (isRate && reader.Name == "key")
                        {
                            fieldname = "key";
                        }

                    
                    }


                    if (reader.NodeType == XmlNodeType.Text)
                    {
                        if (fieldname == "currency")
                        {
                            Currency = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "sort")
                        {
                            SortBy = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "order")
                        {
                            OrderBy = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "count")
                        {
                            RecCount = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "filtered_count")
                        {
                            FilteredCount = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "total_count")
                        {
                            TotalCount = reader.ReadString();
                            fieldname = "";
                        }
                      
                        if (fieldname == "id")
                        {
                            ID = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "name")
                        {
                            HotelName = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "description")
                        {
                            Description = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "stars")
                        {
                            Stars = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "address")
                        {
                            Address = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "image")
                        {
                            Image = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "satisfaction")
                        {
                            Satisfaction = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "rank")
                        {
                            Rank = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "latitude")
                        {
                            Latitude = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "longitude")
                        {
                            Longitude = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "type")
                        {
                            Type = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "num_reviews")
                        {
                            Num_Reviews = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "num_positive_reviews")
                        {
                            Num_Positive_Reviews = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "num_negative_reviews")
                        {
                            Num_Negative_Reviews = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "num_neutral_reviews")
                        {
                            Num_Neutral_Reviews = reader.ReadString();
                            fieldname = "";

                            isHotel = false;
                        }                     

                        //Rates
                        if (fieldname == "price")
                        {
                            Price = float.Parse(reader.ReadString());
                            fieldname = "";
                        }

                        if (fieldname == "tax")
                        {
                            isTax = bool.Parse(reader.ReadString());
                            fieldname = "";

                        }

                        if (fieldname == "on_request")
                        {
                            onRequest = bool.Parse(reader.ReadString());
                            fieldname = "";

                        }

                        if (fieldname == "ratedescription")
                        {
                            RateDescription = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "partner")
                        {
                            Partner = reader.ReadString();
                            fieldname = "";
                        }

                        if (fieldname == "key")
                        {
                            KeyId = reader.ReadString();
                            fieldname = "";

                            isHotel = false;
                        }    

                    }

                  
                    //if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "hotel")

                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "amenities")
                    {
                        isHotel = false;
                        wegoinfo.ViewId = Convert.ToInt64(cxsearchid);
                        wegoinfo.Currency = Currency;
                        wegoinfo.SortBy = SortBy;
                        wegoinfo.OrderBy = OrderBy;
                        wegoinfo.RecCount = int.Parse(RecCount);
                        wegoinfo.FilteredCount = int.Parse(FilteredCount);
                        wegoinfo.TotalCount = int.Parse(TotalCount);

                        wegoinfo.ID = ID;
                        wegoinfo.HotelName = HotelName;
                        wegoinfo.Description = Description;
                        wegoinfo.Stars = Stars;
                        wegoinfo.Address = Address;
                        wegoinfo.Image = Image;
                        wegoinfo.Satisfaction = Satisfaction;
                        wegoinfo.Rank = Rank;
                        wegoinfo.Latitude = Latitude;
                        wegoinfo.Longitude = Longitude;
                        wegoinfo.Type = Type;
                        wegoinfo.Num_Reviews = int.Parse(Num_Reviews);
                        wegoinfo.Num_Positive_Reviews = int.Parse(Num_Positive_Reviews);
                        wegoinfo.Num_Negative_Reviews = int.Parse(Num_Negative_Reviews);
                        wegoinfo.Num_Neutral_Reviews = int.Parse(Num_Neutral_Reviews);

                        cxhotelid = wegodb.Insert(wegoinfo);

                        ID = "";
                        HotelName = "";
                        Description = "";
                        Stars = "";
                        Address = "";
                        Image = "";
                        Satisfaction = "";
                        Rank = "";
                        Latitude = "";
                        Longitude = "";
                        Type = "" ;
                        Num_Reviews = "0";
                        Num_Positive_Reviews = "0";
                        Num_Negative_Reviews = "0";
                        Num_Neutral_Reviews = "0";
                    }

                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "rate")
                    {
                        isRate = false;

                        wegorateinfo.HotelsId = cxhotelid;
                        wegorateinfo.Price = Price;
                        wegorateinfo.Tax = isTax;
                        wegorateinfo.OnRequest = onRequest;
                        wegorateinfo.Description = RateDescription;
                        wegorateinfo.Partner = Partner;
                        wegorateinfo.KeyId = KeyId;

                        wegoratedb.Insert(wegorateinfo);

                        Price = 0;
                        isTax = false;
                        onRequest = false;
                        RateDescription = "";
                        Partner = "";
                        KeyId = "";

                    }

                    
                }

                reader.Close();
                isDone = true;

            }
            catch (Exception Ex)
            {
                isDone = false;
                Ex.ToString();
                CreateExceptionLog(Ex, "HotelsResultsXMLtoTable");
            }

            return isDone;
        }


        public DataSet GetHotelDetails(string hotelid, string searchid)
        {
            string _result = "";

            DataSet _dsHotels = new DataSet();

            try
            {

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://www.wego.com/api/hotels/show/hotel_id/" + hotelid + @"?search_id =" + searchid + "&lang=en&format=xml&api_key=" + API_KEY + "&currency=SGD");

                //http://www.wego.com/api/hotels/show/hotel_id
                req.Method = "GET";
                req.Referer = "http://www.comparexpress.com";
                HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader answer = new StreamReader(stream);

                _dsHotels = new DataSet("DsList");
                _dsHotels.ReadXml(stream);

                //_result = answer.ReadToEnd();
            }
            catch (WebException Wex)
            {
                CreateExceptionLog(Wex, "DataSet GetHotelResults(string hotelid, string searchid)");
            }
            catch (Exception Ex)
            {
                CreateExceptionLog(Ex, "DataSet GetHotelResults(string hotelid, string searchid)");
            }

            return _dsHotels;
        }

        private string GetResponse(string StrURL)
        {
            string strReturn = "";
            HttpWebRequest objRequest = null;
            IAsyncResult ar = null;
            HttpWebResponse objResponse = null;
            StreamReader objs = null;
            try
            {

                objRequest = (HttpWebRequest)WebRequest.Create(StrURL);
                objRequest.Method = "GET";
                objRequest.Referer = "http://www.comparexpress.com";
                objRequest.ReadWriteTimeout = 3600 * 1000;

                ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);

                //// Wait for request to complete

                ar.AsyncWaitHandle.WaitOne(1000 * 60, true);
                if (objRequest.HaveResponse == false)
                {
                    throw new Exception("No Response!!!");
                }

                objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);

                objs = new StreamReader(objResponse.GetResponseStream());
                strReturn = objs.ReadToEnd();

            }
            catch (Exception exp)
            {
                if (exp.Message == "The remote server returned an error: (502) Bad Gateway.")
                {
                    strReturn = "(502) Bad Gateway";
                }
                //throw exp;
            }
            finally
            {
                if (objResponse != null)
                    objResponse.Close();

                if (objs != null)
                {
                    objs.Close();
                    objs = null;
                }
                
                objRequest = null;
                ar = null;
                objResponse = null;

            }
            return strReturn;
        }

        protected void GetScrapingResponse(IAsyncResult result)
        {

        }

        private void CreateExceptionLog(Exception Ex, string strLocation)
        {
            String[] _fileContent = new String[6];
            _fileContent[0] = "Source : " + Ex.Source;
            _fileContent[1] = "Date Time : " + CE.Global.General.GetUTCDateTime().ToString();
            _fileContent[2] = "Stack Trace :" + Ex.StackTrace.ToString();
            _fileContent[3] = "Target Site : " + Ex.TargetSite.ToString();
            _fileContent[4] = "Location : " + "CE.Database.MyDatabase - " + strLocation;
            _fileContent[5] = "Message : " + Ex.Message;

            WriteExceptionLog("WegoHotels_", _fileContent);
        }

        private void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                MyIO _newFile = new MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = CE.Global.General.GetUTCDateTime().Year.ToString("0000") + CE.Global.General.GetUTCDateTime().Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + CE.Global.General.GetUTCDateTime().Day.ToString("00") + CE.Global.General.GetUTCDateTime().Second.ToString("00") + CE.Global.General.GetUTCDateTime().Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }
    }
}

